#parse the output of the Morgan tool
package MorganOutputParser;
use IOutputParser;
use strict;
our @ISA = qw(IOutputParser);    # inherits from IOutputParser

#constructor
sub new {
    my ($class) = @_;
    #call the constructor of the parent class, IOutputParser.
    my $self = $class->SUPER::new();
    bless $self, $class;
    return $self;
}

#inherited from IOutputParser
sub parseOutput{
	my ($self, $datWrapper, $pedWrapper, $outputFile, $currentMarkers, $currFamily) = @_;

	open MORGANRES, $outputFile;
	my @morganData = <MORGANRES>;
	close MORGANRES;
	
	#for each person (for each 2 lines in file)
	while ($#morganData > -1) {
		#get 2 line (each person has 2 lines in the output file)
		my $line1   = shift @morganData;
		my $line2   = shift @morganData;
		my @values1 = split ' ' , $line1;
		my @values2 = split ' ' , $line2;
		#each line begins with person's name- in the format "<family>_<num>"
		my @nameData = split '_' , $values1[0];
		my $familyNumber = $nameData[0];
		($familyNumber eq $currFamily) || next;
		my $personNum    = $nameData[1];
		#after name was read- ignore the name and the first column (always "0")
		shift @values1;
		shift @values1;
		shift @values2;
		shift @values2;
		
		#the following code computs in parallel both of the label strands
		#the first label in the first strand
		my $currentLabel1 = $values1[0];
		#number of recombinations for this person in first strand (saved in 4th column)
		my $numOfRecombinations1 = $values1[1];
		#recombination counter
		my $doneRecombinations1 = 0;
		#iterator
		my $i1 = 2;
		
		#same parameters for second strand
		my $currentLabel2 = $values2[0];
		my $numOfRecombinations2 = $values2[1];
		my $doneRecombinations2 = 0;
		my $i2 = 2;
		
		#for each marker in current markers- compute label
		for my $markerNum (@{$currentMarkers}){
			#first strand
			if ( $doneRecombinations1 < $numOfRecombinations1){#while recombination were not finished
				if ($markerNum == $values1[$i1]){#if recombination happened in current marker
					$currentLabel1 = $values1[$i1+1];#change label acording to current recombination
					$i1 +=2;#increase iterator
					$doneRecombinations1 +=1;#increase nmber of recombinations
				}
			}	
			#same is done for second strand
			if ( $doneRecombinations2 < $numOfRecombinations2){
				if ($markerNum == $values2[$i2]){
					$currentLabel2 = $values2[$i2+1];
					$i2 +=2;
					$doneRecombinations2 +=1;
				}
			}	
			#save cell
			my $cellData = CellData->new();	
			#morgan reports first the label of the mother, then the label for the father. 
			#So- reversed the values.
			$cellData->val1($currentLabel2);
			$cellData->val2($currentLabel1);
			$self->addLabelCell($cellData, $personNum, $datWrapper->getMarkerName("$markerNum"));
		}	
	}	
}

#inherited from IOutputParser
sub parseAlleles{
	die "Morgan tool does not produce alleled table!";
}

1;
